<template>
  <!-- <center style="width: 100%;"> -->
    <!-- <div style="text-align: center; flex-grow: 1"> -->
  <SearchForm  @handleReset="resetForm()" @handleSearch="submitQueryForm(queryFormRef)">
    <el-form ref="queryFormRef" :inline="true" :model="formInline" class="demo-form-inline" >
      <!-- form表单的prop要卸载<el-form-item>标签中，对应里面<input>标签的model的值，这样才能使用reset重置和submit时的参数校验 -->
        <el-form-item>
        <el-select v-model="formInline.topicType"
          clearable
          style="width: 200px;"
          placeholder="请输入习题类型"
        >   
          <el-option
            v-for="item in topicTypeList"
            :key="item.topicType"
            :label="item.topicTypeDesc"
            :value="item.topicType"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-input v-model="formInline.title" placeholder="请输入题目" clearable />
      </el-form-item>
      <el-form-item>
        <el-input v-model="formInline.answer" placeholder="请输入答案" clearable />
      </el-form-item>
      <!-- 校验规则可以直接写在<el-form-item>标签中，如果参数比较多，可以写在<el-form>中，例子在dialog中，注意数字规则的校验在<input>标签中v-model.number要加上.number，不然输入数字还是会提示错误信息 -->
      <el-form-item :rules="[
        { type: 'number', message: '排序只能输入数字' }
      ]">
        <el-input type="text" v-model.number="formInline.indexOrder" placeholder="请输入排序" autocomplete="off" clearable />
      </el-form-item>
      <!-- <el-form-item label="收藏" prop="isStar" >
        <el-switch v-model="formInline.isStar" />
      </el-form-item>
      <el-form-item label="已掌握" prop="isFallible" >
        <el-switch v-model="formInline.isFallible" />
      </el-form-item> -->
      <el-form-item>
        <el-select v-model="formInline.labelIdList" style="width: 200px;" multiple placeholder="请选择标签" clearable filterable >
          <el-option v-for="item in labelList" :key="item.id" :label="item.labelName" :value="item.id"/>
        </el-select>
      </el-form-item>
    </el-form>
    <template #header>
      <!-- <div> -->
        <!-- <el-form-item> -->
        <!-- <el-button type="primary" @click="submitQueryForm(queryFormRef)">查询</el-button> -->
        <!-- <el-button @click="resetForm(queryFormRef)">重置</el-button> -->
        <el-button type="primary" @click="onAddOrUpdate()">新增</el-button>
        <el-button type="primary" @click="importTopic()">导入</el-button>
      <!-- </el-form-item> -->
      <!-- </div> -->
    </template>
  </SearchForm>
  <el-scrollbar>
    <!-- <div class="tableButton"> -->
    <el-form class="tableButton" :model="markForm" ref="markFormRef">
      <el-form-item prop="markLabelId" :rules="[
        { required: true, message: '批量标记的标签不能为空', trigger: 'blur' }
      ]">
        <el-select v-model="markForm.markLabelId" style="width: 200px;margin-right: 12px;" placeholder="请选择批量标记的标签" clearable filterable >
          <el-option v-for="item in labelList" :key="item.id" :label="item.labelName" :value="item.id"/>
        </el-select>
        <el-button type="primary" @click="markLabelBatchForm(markFormRef, true)">批量标记标签</el-button>
        <el-button type="primary" @click="markLabelBatchForm(markFormRef, false)">批量取消标记标签</el-button>
      </el-form-item>
    </el-form>
    <!-- </div> -->
    <div class="table">
    <el-table ref="tableRef" :data="tableData" border stripe >
      <!-- <el-table-column label="ID" prop="id" align="center" width="100"/> -->
      <el-table-column type="selection" min-width="3%"/>
      <el-table-column label="排序" prop="indexOrder" align="center" min-width="5%"/>
      <el-table-column label="习题类型" prop="topicTypeDesc" align="center" min-width="10%"/>
      <el-table-column label="题目" prop="title" align="center"  min-width="20%"/>
      <el-table-column label="答案" prop="answer" align="center"  min-width="25%" />
      <!-- <el-table-column label="标签" prop="labelNames" align="center" >
        <template #default="scope">
          <el-button :type="scope.row.labelNames.includes('1') ? 'success':'default'" @click="updateLabelTopic(1, scope.row)" :icon="Star" circle />
          <el-button :type="scope.row.labelNames.includes('2') ? 'success':'default'" @click="updateLabelTopic(2, scope.row)" :icon="Select" circle />
        </template>
      </el-table-column> -->
      <el-table-column label="自定义标签" prop="labelList" align="center" min-width="10%">
        <template #default="scope">
          {{ formatLabel(scope.row.labelList) }}
        </template>
      </el-table-column> 
      <el-table-column label="默认标签" prop="labelList" align="center"  min-width="10%">
        <template #default="scope">
          <el-button :type="labelStatus(scope.row.labelList, 1)" @click="updateLabelTopic(1, scope.row)" :icon="Star" circle />
          <el-button :type="labelStatus(scope.row.labelList, 2)" @click="updateLabelTopic(2, scope.row)" :icon="Select" circle />
        </template>
      </el-table-column> 
      <!-- <el-table-column label="创建时间" prop="createTime" align="center" min-width="15%">
        <template #default="scope">
          {{ formatDate(scope.row.createTime) }}
        </template>
      </el-table-column> -->
      <el-table-column label="操作" min-width="10%" align="center">
        <template #default="scope">
          <el-button type="primary" link @click="onAddOrUpdate(scope.row)">编辑</el-button>
          <el-button type="danger" link @click="onDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页，
      background是样式，就是分页有背景色，
      layout就是分页插件展示的内容，且按照配置的顺序，total-总条数，prev-前一页按钮，pager-页数按钮，next-后一页按钮，sizes-设置每页展示多少条的可选项，
      :total就是数据总条数，在查询表数据时返回的，并给total参数赋值了，
      current-page就是当前页，绑定formInline的page参数，查询的时候就可以直接拿到值传参了，
      page-size就是每页条数，绑定formInline的size参数，查询的时候就可以直接拿到值传参了，
      @size-change就是改变每页条数时触发的事件，
      @current-change就是改变页数时触发的事件
      -->
    <el-pagination 
      background 
      layout="total, prev, pager, next, sizes" 
      :total="total"
      v-model:current-page="formInline.page" 
      v-model:page-size="formInline.size"  
      :page-sizes="[10, 20, 50, 100]" 
      @size-change="submitQueryForm(queryFormRef)"
      @current-change="submitQueryForm(queryFormRef)"
    />
    </div>

  </el-scrollbar>
  <!-- </center> -->

  <!--新增编辑的弹框-->
  <el-dialog v-model="isShowDialog" :title="updateForm.id ? '编辑' : '新增'" width="600" :before-close="closeDialog">
    <!-- 校验规则为rules，直接定义所有参数的rules，但是<el-form-item>中的prop还是要设置，且还需要新增一个interface -->
    <el-form ref="updateFormRef" :model="updateForm" :rules="rules">
      <el-form-item label="习题类型" :label-width="formLabelWidth" prop="topicType">
        <el-select v-model="updateForm.topicType"
          clearable
          placeholder="请输入习题类型"
        >   
          <el-option
            v-for="item in topicTypeList"
            :key="item.topicType"
            :label="item.topicTypeDesc"
            :value="item.topicType"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="题目" :label-width="formLabelWidth" prop="title">
        <el-input v-model="updateForm.title" placeholder="请输入题目"/>
      </el-form-item>
      <el-form-item label="答案" :label-width="formLabelWidth" prop="answer">
        <el-input type="textarea" :rows="5" v-model="updateForm.answer" placeholder="请输入答案"/>
      </el-form-item>
      <el-form-item label="排序" :label-width="formLabelWidth" prop="indexOrder">
        <el-input v-model.number="updateForm.indexOrder" placeholder="请输入排序"/>
      </el-form-item>
      <el-form-item label="标签" :label-width="formLabelWidth" prop="labelIdList">
        <el-select v-model="updateForm.labelIdList" multiple placeholder="请选择标签" clearable filterable >
          <el-option v-for="item in labelList" :key="item.id" :label="item.labelName" :value="item.id"/>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog()">取消</el-button>
        <el-button type="primary" @click="submitUpdateForm(updateFormRef)">确认</el-button>
      </div>
    </template>
  </el-dialog>

    <!--导入的弹框-->
  <el-dialog v-model="isShowImportDialog" title='导入习题' width="600" :before-close="closeImportDialog">
    <el-button style="margin-bottom: 10px;" @click="downloadImportModel()">下载导入模板</el-button>
    <!-- <el-form-item label="导入文件" prop="fileId"> -->
      <el-upload ref="importRef"
      :file-list="importData.fileList"
      :action="importData.importUrl"
      :limit="1"
      :headers="importData.headers"
      list-type="text"
      accept=".xls,.xlsx"
      class="avatar-uploader"
      :before-upload="checkImportFile"
      :name="importData.fileName"
      :on-success="importResult"
      >
      <!-- <div class="uploadIcon">
        <el-icon>
          <Plus />
        </el-icon>
      </div> -->
      <!-- <el-button type="primary">导入习题</el-button> -->
      
      <template #trigger>
        <el-button type="primary" @click="importData.fileList = []">上传</el-button>
      </template>
    
      <template #tip>
        <div class="el-upload__tip text-red">只能导入xls/xlsx文件，导入数据根据导入模板填写，需携带表头</div>
      </template>
      </el-upload>
    <!-- </el-form-item> -->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeImportDialog()">关闭</el-button>
      </div>
    </template>
  </el-dialog>
<!-- </div> -->
</template>

<script lang="ts" setup>
import { reactive,ref } from 'vue';
import { urlIp } from '../../composables/value';
import type { FormInstance, FormRules } from 'element-plus';
import {
  Star,CircleClose,CloseBold,Select
} from '@element-plus/icons-vue';
// import {updateLabelTopic} from './RandomPractice.vue';
import { ElMessage } from 'element-plus';
import { formatDate, postWithToken, getDownloadFile } from '../../composables/utils';
import { useUsersStore } from '~/store/user';
import SearchForm from '../layouts/SearchForm.vue';

// const route = useRoute();
// const topicType = ref<number | null>(null);
// const getTopicType = () => {
//   if (route.fullPath === '/topic/topicManage') {
//     topicType.value = 1;
//   } else if (route.fullPath === '/topicElect/topicManage') {
//     topicType.value = 2;
//   } 
// }
// getTopicType();
const userStore = useUsersStore();
const topicTypeList = ref<TopicType[]>();
const getTopicTypeList = async () => {
  const response = await postWithToken('/topicType/queryTopicType');
  if (response.code == 200) {
      topicTypeList.value = response.data;
    }
}
interface TopicType {
  topicType: number,
  topicTypeDesc: string
}
const labelList = ref<any>();
const tableRef = ref();
// const markLabelId = ref<any>();

// 批量标记标签的form
const markForm = reactive({
  markLabelId: ''
});
const markFormRef = ref<FormInstance>();

getTopicTypeList();

// 列表查询的form
const formInline = reactive({
  title: '',
  answer: '',
  indexOrder: '',
  isFallible: false,
  isStar: false,
  topicType: '',
  labelIdList:[],
  page: 1,
  size: 10
});
const tableData = ref<any>(null);
const total = ref<number>(0);
// 展示弹框的参数
const isShowDialog = ref(false);
const isShowImportDialog = ref(false);
// 弹框里面label的宽度
const formLabelWidth = '80px';

// 弹框里面的form对应的interface
interface UpdateRuleForm {
  id:number | null;
  answer: string;
  title:string;
  topicType:number | '';
  indexOrder:number | null;
  labelIdList:number[];
}
// 弹框里面的form
const updateForm = reactive<UpdateRuleForm>({
    id:null,
    answer: '',
    title:'',
    topicType: '',
    indexOrder:null,
    labelIdList:[]
});
// 对应form的引用，在重置form和验证form需要用到
const queryFormRef = ref<FormInstance>();
const updateFormRef = ref<FormInstance>();
// 弹框的form校验规则
const rules = reactive<FormRules<UpdateRuleForm>>({
  indexOrder: [
    { type: 'number', message: '排序只能输入数字', trigger: 'blur' },
  ],
  answer: [
    { required: true, message: '答案不能为空', trigger: 'blur'}
  ],
  title: [
    { required: true, message: '题目不能为空', trigger: 'blur'}
  ],
  topicType: [
    { required: true, message: '习题类型不能为空', trigger: 'blur'}
  ],
});

const importData = reactive({
  fileList: [],
  importUrl: urlIp.value + '/topic/importTopic',
  fileName: 'file',
  headers: {token: userStore.token}
});

// 分页查询
const onSubmit = async () => {
  try {
    const response = await postWithToken('/topic/pageTopic', formInline);
    if (response.code != 200) {
        ElMessage.error(response.msg);
    } else {
      // 设置表数据
      tableData.value = response.data;
      // 设置分页参数的total
      total.value = response.total;
    }
  } catch (error) {
    console.error('There was an error!', error);
  }
};

// 新增或更新的弹框输入框赋值
const onAddOrUpdate = (data?: any) => {
  // 展示弹框
  isShowDialog.value = true;
  if (data != undefined) {
    updateForm.id = data.id;
    updateForm.answer = data.answer;
    updateForm.title = data.title;
    updateForm.indexOrder = data.indexOrder;
    updateForm.topicType = data.topicType;
    updateForm.labelIdList = getLabelIdList(data.labelList);
  }
};

// 新增更新数据
const addOrUpdateTopic =  async () => {
  try {
    var url = '/topic/saveTopic';
    if (updateForm.id) {
      url = '/topic/updateTopic';
    }
    const response = await postWithToken(url, updateForm);
    if (response.code != 200) {
        ElMessage.error(response.msg);
    }
    closeDialog();
    submitQueryForm(queryFormRef.value);
  } catch (error) {
    console.error('There was an error!', error);
  }
};

function closeDialog() {
  isShowDialog.value = false;
  clearForm();
}
// 重置数据
const clearForm = () => {
  // updateForm.id = null;
  // if (!formEl) return
  // formEl.resetFields()
  updateForm.id = null;
  updateForm.answer = '';
  updateForm.title = '';
  updateForm.indexOrder = null;
  updateForm.topicType = '';
  updateForm.labelIdList = [];
}

// function clearForm() {
//   form.id = '';
//   form.answer = '';
//   form.indexOrder = '';
//   form.title = '';
// }

// 删除数据
const onDelete = async (data?: any) => {
  try {
    const response = await postWithToken('/topic/deleteTopic', data);
    if (response.code != 200) {
        ElMessage.error(response.msg);
    }
    submitQueryForm(queryFormRef.value);
  } catch (error) {
    console.error('There was an error!', error);
  }
};


const submitQueryForm = (formEl: FormInstance | undefined) => {
  if (!formEl) {
    onSubmit();
    return
  }
  formEl.validate((valid) => {
    if (valid) {
      onSubmit();
    } else {
      console.log('error submit!')
    }
  })
}

// 打开页面就执行一次查询
onSubmit();

const resetForm = () => {
  // if (!formEl) return
  // formEl.resetFields()
  formInline.topicType = '';
  formInline.labelIdList = [];
  formInline.title= '';
  formInline.answer= '';
  formInline.indexOrder= '';
}

const submitUpdateForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      addOrUpdateTopic();
    } else {
      console.log('error submit!')
    }
  })
};

  // 更新标记（收藏、已掌握）
  // labelId 1-收藏 2-已掌握
  // isMarkLabel true-标记 false-取消
  const updateLabelTopic = async (labelId : number, row : any) => {
    const updateLabelTopicData = {
      topicIdList: [row.id],
      labelId: labelId,
      isMarkLabel: !getLabelIdList(row.labelList).includes(labelId)
    };
    const response = await postWithToken('/label/updateLabelTopic', updateLabelTopicData);
      if (response.code == 200) {
        // if (labelType == 1) {
        //   isMarkLabel ? starStatus.value = 'success' : starStatus.value = 'default';
        // } else if (labelType == 2) {
        //   isMarkLabel ? fallibleStatus.value = 'success' : fallibleStatus.value = 'default';
        // }
        submitQueryForm(queryFormRef.value);
      } else {
        ElMessage.error(response.msg);
      }
  }

const importTopic = () => {
  // 展示导入弹框
  isShowImportDialog.value = true;
};

const closeImportDialog = () => {
  // 清空导入的文件，否则再次导入文件就不会调接口了
  importData.fileList = [];
  // 关闭导入弹框
  isShowImportDialog.value = false;
  // 刷新列表
  onSubmit();
}

// 下载导入模板文件
const downloadImportModel = async () => {
  // window.open(urlIp.value + '/topic/downloadImportModel', '_blank', 'headers={"token":""' + userStore.token + '""}');
  getDownloadFile('/topic/downloadImportModel');
}

// 检查导入文件大小
const checkImportFile = (file: any) => {
  const isLt5M = file.size / 1024 / 1024 < 5;
  if (!isLt5M) {
    ElMessage.warning('上传文件大小不能超过5MB!');
  }
}

// 导入文件
const importResult = (response:any, file:any, fileList:any) => {
  if (response.code != 200) {
    ElMessage.error(response.msg);
  } else {
    ElMessage.success('导入成功');
  }
}


const listLabel = async () => {
  var response = await postWithToken('/label/queryLabel', {});
  if (response.code != 200) {
    ElMessage.error(response.msg);
  } else {
    // 所有的角色
    labelList.value = response.data;
    // 已选择的角色
    // updateForm.labelIdList = response.data.filter((item:any) => item.selected).map((item:any) => item.id);
  }
}
listLabel();

const formatLabel = (labelList : [any]) => {
  if (labelList === null || labelList === undefined) {
    return '';
  }
  var labelName = labelList.filter(item => item.id != 1 && item.id != 2).map((item) => item.labelName).join(',');
  return labelName;
}

const labelStatus = (labelList : [any], labelId:number) => {
  return labelList != null && labelList != undefined && labelList.some(item => item.id === labelId) ? 'success':'default';
}

const getLabelIdList = (labelList : {id:number;labelName:string}[] | null) => {
  if (labelList === null || labelList === undefined) {
    return [];
  }
  return labelList.map(item => item.id);
}

const getTopicIdList = (topicList : [any]) => {
  return topicList.map(topic => topic.id);
}

const markLabelBatchForm = (formEl: FormInstance | undefined, isMarkLabel : boolean) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      markLabelBatch(isMarkLabel);
    } else {
      console.log('error submit!')
    }
  })
}

const markLabelBatch = async (isMarkLabel : boolean) => {
  // 勾选的习题id
  const selectTopicIdList = getTopicIdList(tableRef.value.getSelectionRows());
  if (!selectTopicIdList || selectTopicIdList.length == 0) {
    ElMessage.error("请勾选需要标记的习题");
    return
  }
  // if (!markLabelId.value) {
  //   ElMessage.error("请选择批量标记的标签");
  //   return
  // }
  const updateLabelTopicData = {
    topicIdList: selectTopicIdList, 
    labelId: markForm.markLabelId,
    isMarkLabel: isMarkLabel
  };
  const response = await postWithToken('/label/updateLabelTopic', updateLabelTopicData);
  if (response.code != 200) {
    ElMessage.error(response.msg);
  } else {
    onSubmit();
  }
};

</script>

<style lang="scss">
/* 为了页面刷新不出现滚动条 */
.ep-scrollbar {
  height: auto;
}
// .tableButton {
//   padding-left: 20px;
//   // padding-bottom: 10px;
//   text-align: justify;
// }
// .table {
//   padding-left: 20px;
//   padding-right: 20px;
//   width: 95%;
// }
// .ep-button {
//   padding: 8px 20px;
// }
</style>